<template>
  <div id="silder-range" :class="rangeStatus ? 'success' : ''">
    <div class="box" @mousedown="rangeMove" :class="rangeStatus ? successIcon : startIcon"></div>
    {{ rangeStatus ? successText : startText }}
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const props = defineProps({
  //成功图标
  successIcon: {
    type: String,
    default: "el-icon-success"
  },
  //成功文字
  successText: {
    type: String,
    default: "验证成功"
  },
  //开始的图标
  startIcon: {
    type: String,
    default: "el-icon-d-arrow-right"
  },
  //开始的文字
  startText: {
    type: String,
    default: "拖动滑块到最右侧"
  }
})
const emit = defineEmits(['failed', 'success'])
let rangeStatus = ref('') as any, disX = ref(0), ele = ref() as any
const rangeMove = (e) => {
  ele.value = e.target;
  let startX = e.clientX;
  let eleWidth = ele.value.offsetWidth;
  let parentWidth = ele.value.parentElement.offsetWidth;
  let MaxX = parentWidth - eleWidth;
  if (rangeStatus.value) {
    return false;
  }
  document.onmousemove = (e) => {
    let endX = e.clientX;
    disX.value = endX - startX;
    if (disX.value <= 0) {
      disX.value = 0;
    }
    if (disX.value >= MaxX - eleWidth) {
      disX.value = MaxX;
    }
    ele.value.style.transition = '.1s all';
    ele.value.style.transform = 'translateX(' + disX.value + 'px)';
    e.preventDefault();
  }
  document.onmouseup = () => {
    if (disX.value !== MaxX) {
      ele.value.style.transition = '.5s all';
      ele.value.style.transform = 'translateX(0)';
      emit("failed", rangeStatus.value);
    } else {
      rangeStatus.value = true;
      emit("success", rangeStatus.value);
    }
    document.onmousemove = null;
    document.onmouseup = null;
  }
}
const initRange = () => {
  rangeStatus.value = ''
  disX.value=0
  ele.value.style.transition = '.5s all';
  ele.value.style.transform = 'translateX(0)';
  emit("failed", rangeStatus.value);
}
defineExpose({
  initRange
})
</script>
<style scoped lang="scss">
#silder-range {
  width: 100%;
  background-color: #e3e4e6;
  position: relative;
  transition: 1s all;
  user-select: none;
  color: #333;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 45px;
  /*no*/
}
.success {
  background-color: #7AC23C !important;
  color: #fff !important;
  .box {
    color: #7AC23C !important;
  }
}
.box {
  position: absolute;
  left: 0;
  width: 60px;
  /*no*/
  height: 100%;
  color: #919191;
  background-color: #fff;
  border: 1px solid #bbb;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
